package com.example.guestbook.servlet;

import com.example.guestbook.pojo.Booklist;
import com.example.guestbook.service.IBooklistService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/addbook")
public class AddBooklistServlet extends HttpServlet
{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("doGet");
        // 用户提交来的编码
        req.setCharacterEncoding("utf-8");
        // 设置响应内容
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();


        // 1. 获取参数
        // 2. 调用service
        // 3. 显示结果/跳转/请求转发




        // 1. 获取参数
        String username = req.getParameter("username");
        String title = req.getParameter("title");
        String note = req.getParameter("note");
        String face = req.getParameter("face");
        Booklist booklist = new Booklist();
        booklist.setUsername(username);
        booklist.setBooknote(note);
        booklist.setBooktitle(title);
        booklist.setBookface(face);

        pw.println(username);
        pw.println(title);

        System.out.println("调用 service");
        // 2. 调用下层
        // 得到Spring从容器,
        // 从容器中获取customerServcie的Bean
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        IBooklistService booklistService = (IBooklistService)applicationContext.getBean("booklistService");
        boolean result = booklistService.add(booklist);


        System.out.println("打印结果");
        // 3.
        pw.println("添加"+(result?"成功":"失败"));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
